import { resolve } from "path";
import { readFile, writeFileSync } from "fs";

// 项目根目录
const rootDir = process.cwd();

const fetchVersionFile = (env) => {
  const versionFileName = `${env}.json`;
  // const __filename = fileURLToPath(import.meta.url)
  // __dirname = dirname(__filename)
  return resolve(rootDir, "version", versionFileName);
};

const versionManage = async (deployConfig) => {
  const { env, deployType } = deployConfig;
  const versionFilePath = fetchVersionFile(env);

  readFile(versionFilePath, "utf8", (err, data) => {
    if (err) throw err;
    const app = JSON.parse(data);
    const verA = app.version.split(".").map((item) => Number(item));

    switch (deployType) {
      case "main":
        verA[0]++;
        verA[1] = 0;
        verA[2] = 1;
        break;
      case "feature":
        verA[1]++;
        verA[2] = 1;
        break;
      case "bugfix":
        verA[2]++;
        break;
    }

    app.version = verA.join(".");
    app.build++;

    // 更新version文件
    writeFileSync(versionFilePath, JSON.stringify(app));

    deployConfig.app = app;
    deployConfig.env = env;
    deployConfig.deployType = deployType;

    // 更新app文件
    const appFilePath = resolve(rootDir, "version", "app.json");
    writeFileSync(appFilePath, JSON.stringify(deployConfig));
  });
};

export default versionManage;
